package cn.lngaosu.lwyd.module.integration.service.weibocommentsshow;

import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollUtil;
import cn.lngaosu.lwyd.framework.common.util.http.HttpUtils;
import cn.lngaosu.lwyd.module.infra.service.config.ConfigService;
import cn.lngaosu.lwyd.module.integration.dal.dataobject.weibostatusesusertimeline.WeiboStatusesUsertimelineDO;
import cn.lngaosu.lwyd.module.integration.dal.mysql.weibostatusesusertimeline.WeiboStatusesUsertimelineMapper;
import cn.lngaosu.lwyd.module.integration.service.apptoken.AppTokenService;
import cn.lngaosu.lwyd.module.integration.service.weibostatusesusertimeline.WeiboStatusesUsertimelineServiceImpl;
import cn.lngaosu.lwyd.module.system.dal.dataobject.webinterfacelog.WebinterfaceLogDO;
import cn.lngaosu.lwyd.module.system.dal.mysql.webinterfacelog.WebinterfaceLogMapper;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import cn.lngaosu.lwyd.module.integration.controller.admin.weibocommentsshow.vo.*;
import cn.lngaosu.lwyd.module.integration.dal.dataobject.weibocommentsshow.WeiboCommentsShowDO;
import cn.lngaosu.lwyd.framework.common.pojo.PageResult;
import cn.lngaosu.lwyd.framework.common.pojo.PageParam;
import cn.lngaosu.lwyd.framework.common.util.object.BeanUtils;

import cn.lngaosu.lwyd.module.integration.dal.mysql.weibocommentsshow.WeiboCommentsShowMapper;

import static cn.lngaosu.lwyd.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.lngaosu.lwyd.framework.common.util.collection.CollectionUtils.convertList;
import static cn.lngaosu.lwyd.framework.common.util.collection.CollectionUtils.diffList;
import static cn.lngaosu.lwyd.module.integration.enums.ErrorCodeConstants.*;

/**
 * 微博评论 Service 实现类
 *
 * @author 张恒
 */
@Service
@Validated
public class WeiboCommentsShowServiceImpl implements WeiboCommentsShowService {
    private static final Logger logger = LoggerFactory.getLogger(WeiboCommentsShowServiceImpl.class);

    @Resource
    private WeiboCommentsShowMapper weiboCommentsShowMapper;
    @Resource
    private AppTokenService appTokenService;
    @Resource
    private ConfigService configService;
    @Resource
    private WebinterfaceLogMapper webinterfaceLogMapper;
    @Resource
    private WeiboStatusesUsertimelineMapper weiboStatusesUsertimelineMapper;

    @Override
    public Long createWeiboCommentsShow(WeiboCommentsShowSaveReqVO createReqVO) {
        // 插入
        WeiboCommentsShowDO weiboCommentsShow = BeanUtils.toBean(createReqVO, WeiboCommentsShowDO.class);
        weiboCommentsShowMapper.insert(weiboCommentsShow);
        // 返回
        return weiboCommentsShow.getId();
    }

    @Override
    public void updateWeiboCommentsShow(WeiboCommentsShowSaveReqVO updateReqVO) {
        // 校验存在
        validateWeiboCommentsShowExists(updateReqVO.getId());
        // 更新
        WeiboCommentsShowDO updateObj = BeanUtils.toBean(updateReqVO, WeiboCommentsShowDO.class);
        weiboCommentsShowMapper.updateById(updateObj);
    }

    @Override
    public void deleteWeiboCommentsShow(Long id) {
        // 校验存在
        validateWeiboCommentsShowExists(id);
        // 删除
        weiboCommentsShowMapper.deleteById(id);
    }

    @Override
        public void deleteWeiboCommentsShowListByIds(List<Long> ids) {
        // 校验存在
        validateWeiboCommentsShowExists(ids);
        // 删除
        weiboCommentsShowMapper.deleteByIds(ids);
        }

    private void validateWeiboCommentsShowExists(List<Long> ids) {
        List<WeiboCommentsShowDO> list = weiboCommentsShowMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(WEIBO_COMMENTS_SHOW_NOT_EXISTS);
        }
    }

    private void validateWeiboCommentsShowExists(Long id) {
        if (weiboCommentsShowMapper.selectById(id) == null) {
            throw exception(WEIBO_COMMENTS_SHOW_NOT_EXISTS);
        }
    }

    @Override
    public WeiboCommentsShowDO getWeiboCommentsShow(Long id) {
        return weiboCommentsShowMapper.selectById(id);
    }

    @Override
    public PageResult<WeiboCommentsShowDO> getWeiboCommentsShowPage(WeiboCommentsShowPageReqVO pageReqVO) {
        return weiboCommentsShowMapper.selectPage(pageReqVO);
    }

    @Override
    public void syncWeiboCommentsShow() {
        // 获取token
        String weiboToken = appTokenService.getWeiboToken();
        if (StringUtils.isEmpty(weiboToken)) {
            throw exception(WEIBO_TOKEN_NOT_EXISTS);
        }

        // 接口配置
        String configValue = configService.getConfigValueByKey("weiboConfig");
        if (StringUtils.isEmpty(configValue)) {
            throw exception(INTERFACE_CONFIG_NOT_EXISTS);
        }

        JSONObject configJo = JSONObject.parseObject(configValue);
        // 接口开关
        String onOff = configJo.getString("onOff");
        if (!"on".equals(onOff)) {
            throw exception(INTERFACE_CONFIG_NOT_EXISTS);
        }

        // 获取地址
        String commentsShowUrl = configJo.getString("commentsShowUrl");
        commentsShowUrl = commentsShowUrl + "?access_token=" + weiboToken;

        // 构造请求参数
        JSONObject params = new JSONObject();

        // 初始化日志数据（默认成功）
        WebinterfaceLogDO webinterfaceLogDO = new WebinterfaceLogDO();
        webinterfaceLogDO.setInterfaceSystemName("微博");
        webinterfaceLogDO.setInterfaceName("根据微博ID返回某条微博的评论列表");
        webinterfaceLogDO.setInterfaceUrl(commentsShowUrl);
        webinterfaceLogDO.setInterfaceRequestMethod("GET");
        webinterfaceLogDO.setInterfaceParam(null);
        webinterfaceLogDO.setInterfaceStatus("成功");
        webinterfaceLogMapper.insert(webinterfaceLogDO);

        // 查询最近一周的微博列表，遍历查询评论
        LambdaQueryWrapper<WeiboStatusesUsertimelineDO> queryWrapper = new LambdaQueryWrapper<>();
        LocalDateTime endLocalDateTime = LocalDateTime.now();
        LocalDateTime beginLocalDateTime = endLocalDateTime.minusDays(7L);
        queryWrapper.between(WeiboStatusesUsertimelineDO::getCreatedAt, beginLocalDateTime, endLocalDateTime);
        List<WeiboStatusesUsertimelineDO> weiboStatusesUsertimelineDOS = weiboStatusesUsertimelineMapper.selectList(queryWrapper);
        for (int i = 0; i < weiboStatusesUsertimelineDOS.size(); i++) {
            WeiboStatusesUsertimelineDO weiboStatusesUsertimelineDO = weiboStatusesUsertimelineDOS.get(i);
            try {
                String result = HttpUtils.get(commentsShowUrl + "&id=" + weiboStatusesUsertimelineDO.getWeiboId(), new HashMap<>());
                // 解析接口结果
                JSONObject resultJo = JSONObject.parseObject(result);
                Integer errcode = resultJo.getInteger("error_code");
                if (ObjectUtils.isNotEmpty(errcode)) {
                    webinterfaceLogDO.setInterfaceStatus("失败");
                    webinterfaceLogDO.setInterfaceErrorInfo(result);
                    webinterfaceLogMapper.updateById(webinterfaceLogDO);
                    continue;
                }

                // 处理接口数据
                JSONArray allJa = new JSONArray();
                JSONArray resultJa = resultJo.getJSONArray("comments");
                allJa.addAll(resultJa);
                Long max_id = resultJo.getLong("max_id");
                while (max_id != 0L) {
                    result = HttpUtils.get(commentsShowUrl + "&id=" + weiboStatusesUsertimelineDO.getWeiboId() + "&max_id=" + max_id, new HashMap<>());
                    // 解析接口结果
                    resultJo = JSONObject.parseObject(result);
                    errcode = resultJo.getInteger("error_code");
                    if (ObjectUtils.isNotEmpty(errcode)) {
                        webinterfaceLogDO.setInterfaceStatus("失败");
                        webinterfaceLogDO.setInterfaceErrorInfo(result);
                        webinterfaceLogMapper.updateById(webinterfaceLogDO);
                        break;
                    }
                    resultJa = resultJo.getJSONArray("comments");
                    allJa.addAll(resultJa);
                    max_id = resultJo.getLong("max_id");
                }
                webinterfaceLogDO.setInterfaceErrorInfo(result);
                webinterfaceLogMapper.updateById(webinterfaceLogDO);


                for (int j = 0; j < allJa.size(); j++) {
                    JSONObject jsonObject = allJa.getJSONObject(j);
                    Long commentId = jsonObject.getLong("id");
                    LocalDate localDate = LocalDate.now();
                    JSONObject userJo = jsonObject.getJSONObject("user");
                    Long authorId = userJo.getLong("id");
                    String screenName = userJo.getString("screen_name");
                    String profileImageUrl = userJo.getString("profile_image_url");
                    WeiboCommentsShowDO weiboCommentsShowDO = BeanUtils.toBeanIgnoreProperties(jsonObject, WeiboCommentsShowDO.class, CopyOptions.create().setIgnoreProperties("id"));
                    weiboCommentsShowDO.setWeiboUid(weiboStatusesUsertimelineDO.getWeiboUid());
                    weiboCommentsShowDO.setWeiboId(weiboStatusesUsertimelineDO.getWeiboId());
                    weiboCommentsShowDO.setSyncDate(localDate);
                    weiboCommentsShowDO.setCommentId(commentId);
                    weiboCommentsShowDO.setAuthorId(authorId);
                    weiboCommentsShowDO.setScreenName(screenName);
                    weiboCommentsShowDO.setProfileImageUrl(profileImageUrl);
                    weiboCommentsShowDO.setDetailMessage(jsonObject.toJSONString());

                    // 判断数据是更新还是插入
                    LambdaQueryWrapper<WeiboCommentsShowDO> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(WeiboCommentsShowDO::getCommentId, commentId);
                    List<WeiboCommentsShowDO> weiboCommentsShowDOS = weiboCommentsShowMapper.selectList(wrapper);
                    if (CollectionUtils.isNotEmpty(weiboCommentsShowDOS)) {
                        weiboCommentsShowDO.setId(weiboStatusesUsertimelineDOS.get(0).getId());
                    }

                    weiboCommentsShowMapper.insertOrUpdate(weiboCommentsShowDO);
                }

            } catch (Exception e) {
                webinterfaceLogDO.setInterfaceStatus("失败");
                webinterfaceLogDO.setInterfaceErrorInfo(e.getMessage());
                webinterfaceLogMapper.updateById(webinterfaceLogDO);
                logger.error("微博【根据微博ID返回某条微博的评论列表】接口调用失败！", e);
            }
        }

    }

}